package com.example.iterable.collection;

import com.example.entity.Product;
import com.google.common.collect.Lists;


import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 沈传尚
 * @date 2021/12/27
 */
/*
Collectors.groupingBy: 根据一个或多个属性对集合中的项目进行分组
 */
public class CollectorsGroupByTest {
    public static void main(String[] args) {

        ArrayList<Product> products = Lists.newArrayList(
                Product.builder().id(1).name("父级").build(),
                Product.builder().id(1).name("子级1").num(3).price(new BigDecimal("5")).category("").build(),
                Product.builder().id(2).name("子级2").num(1).price(new BigDecimal("6")).category("").build(),
                Product.builder().id(1).name("子级3").num(2).price(new BigDecimal("7")).category("").build());

        Map<Integer, List<Product>> map = products.stream().collect(Collectors.groupingBy(Product::getId));
        Set<Map.Entry<Integer, List<Product>>> entries = map.entrySet();
        for (Map.Entry<Integer, List<Product>> m :entries){
            Integer key = m.getKey();
            List<Product> value = m.getValue();
            System.out.println(key+":"+value);
        }


        products.stream().forEach(product -> {
            TreeSet<Product> set=new TreeSet<>(Comparator.comparingInt(Product::getNum));
            set.addAll(map.get(product.getId()));
            product.setChildren(set);
        });

        map.getOrDefault(0,new ArrayList<Product>());

    }
}
